package com.yami.shop.admin.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Mp;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.MpService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/sys/mp")
public class MpController {
	@Autowired
	private MpService mpService;

	/**
	 * 分页查询
	 *
	 * @param page    分页对象
	 * @param
	 * @return 分页数据
	 */
	@GetMapping("/page")
	public ServerResponseEntity<IPage<Mp>> getMpPage(PageParam<Mp> page, Mp mp) {
		IPage<Mp> mpPage = mpService.page(
				page, new LambdaQueryWrapper<Mp>()
						
						.like(mp.getName()  != null, Mp::getName, mp.getName()) );

		return ServerResponseEntity.success(mpPage);

	}


	/**
	 * 通过id查询公众号
	 *
	 * @param id id
	 * @return 单个数据
	 */
	@GetMapping("/info/{id}")
	public ServerResponseEntity<Mp> getById(@PathVariable("id") Long id) {
		return ServerResponseEntity.success(mpService.getById(id));
	}

	/**
	 * 新增
	 *
	 * @
	 * @return 是否新增成功
	 */
	@SysLog("新增公众号")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys:mp:save')")
	public ServerResponseEntity<Boolean> save(@RequestBody @Valid Mp mp) {
		// 查看是否相同的标签
		List<Mp> list = mpService.list(new LambdaQueryWrapper<Mp>().like(Mp::getName, mp.getName()));
		if (CollectionUtil.isNotEmpty(list)) {
			throw new YamiShopBindException("公众号已存在，不能添加相同的公众号");
		}

		return ServerResponseEntity.success(mpService.save(mp));
	}

	/**
	 * 修改公众号
	 *
	 * @  公众号
	 * @return 是否修改成功
	 */
	@SysLog("修改公众号")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys:mp:update')")
	public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Mp mp) {

		return ServerResponseEntity.success(mpService.updateById(mp));
	}

	/**
	 * 通过id删除公众号
	 *
	 * @param ids
	 *  @return 是否删除成功
	 */
	@SysLog("删除公众号")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('sys:mp:delete')")
	public ServerResponseEntity<Boolean> removeById(@RequestBody Long[] ids) {
		for (Long id : ids) {
			mpService.removeById(id);
		}
		//prodTagService.removeProdTag();
		return ServerResponseEntity.success();
	}

	@GetMapping("/listMpList")
	public ServerResponseEntity<List<Mp>> listMpList() {

		return ServerResponseEntity.success(mpService.list());

	}
}
